<template>
	<view class="trajectory-container">
		<map id="trajectoryMap" v-if="latitude && longitude" :latitude="latitude" :longitude="longitude" :scale="14"
			class="map-area" :markers="markers" :polyline="polyline" show-location></map>
		<view class="info-card">
			<view class="address-item flex u-line-1">
				<text class="address-label">出发地：</text>
				<text class="value">{{ startAddress || '暂无数据' }}</text>
			</view>
			<view class="address-item flex u-line-1">
				<text class="address-label">目的地：</text>
				<text class="value">{{ destinationAddress || '暂无数据' }}</text>
			</view>
			<view class="coords flex u-line-1">
				<text>当前经度：</text>
				<text class="value">{{ longitude ? longitude : '获取中...' }}</text>
			</view>
			<view class="coords flex u-line-1">
				<text>当前纬度：</text>
				<text class="value">{{ latitude ? latitude : '获取中...' }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import commonApi from '@/api/common.js'
	export default {
		data() {
			return {
				latitude: null,
				longitude: null,
				markers: [],
				locationWatcher: null,
				startAddress: '', // 出发地地址
				startLocation: null, // 出发地经纬度
				destinationAddress: '', // 目的地地址
				destinationLocation: null, // 目的地经纬度
				polyline: [], // 路线
				data: {}
			};
		},
		onLoad(e) {
			if (this.latitude && this.longitude) {
				this.startLocationWatch();
			}
			if (e.data) {
				this.data = JSON.parse(e.data)
				console.log('接收到的数据:', this.data)
				this.getInitialAddress()
			}
			this.checkAndGetLocation();
		},
		onUnload() {
			// 页面卸载时清理定位监听
			this.stopLocationWatch();
		},
		methods: {
			//获取初始出发地跟目的地经纬信息
			getInitialAddress(){
				try {
					this.startAddress = this.data.origin
					// 处理出发地经纬度字符串
					if (this.data.originLocation && typeof this.data.originLocation === 'string') {
						const [lat, lng] = this.data.originLocation.split(',')
						this.startLocation = {
							latitude: Number(lat),
							longitude: Number(lng)
						}
					}
				
					this.destinationAddress = this.data.destination
					// 处理目的地经纬度字符串
					if (this.data.destinationLocation && typeof this.data.destinationLocation === 'string') {
						const [lat, lng] = this.data.destinationLocation.split(',')
						this.destinationLocation = {
							latitude: Number(lat),
							longitude: Number(lng)
						}
					}
				
					// 设置初始位置为出发地位置
					if (this.startLocation && !isNaN(this.startLocation.latitude) && !isNaN(this.startLocation
						.longitude)) {
						this.latitude = this.startLocation.latitude
						this.longitude = this.startLocation.longitude
						// 更新地图标记和路线
						this.updateMarkers()
						this.updatePolyline()
					}
				
					console.log('处理后的起点位置:', this.startLocation)
					console.log('处理后的终点位置:', this.destinationLocation)
				} catch (error) {
					console.error('数据解析错误:', error)
				}
			},
			checkAndGetLocation() {
				uni.getSetting({
					success: (res) => {
						if (res.authSetting && res.authSetting["scope.userLocation"]) {
							this.getLocation();
						} else {
							this.requestLocationAuth();
						}
					},
				});
			},
			requestLocationAuth() {
				uni.authorize({
					scope: "scope.userLocation",
					success: () => {
						this.getLocation();
					},
					fail: () => {
						uni.showModal({
							title: "提示",
							content: "需要获取您的地理位置，请授权",
							showCancel: false,
							success: () => {
								uni.openSetting({
									success: (settingRes) => {
										if (settingRes.authSetting[
												"scope.userLocation"]) {
											this.getLocation();
										}
									}
								});
							},
						});
					},
				});
			},
			getLocation() {
				wx.getLocation({
					type: "gcj02",
					isHighAccuracy: true,
					success: (res) => {
						console.log('获取位置成功:', res);
						// 保存初始位置
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						// 设置默认出发地
						this.startLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						// 获取初始位置的地址
						this.getAddressByLocation(res.latitude, res.longitude, true);

						// 上传初始位置信息
						this.uploadLocationInfo(res.latitude, res.longitude);
					},
					fail: (error) => {
						console.error('获取位置失败:', error);
						this.checkAndGetLocation();
					},
				});
			},
			startLocationWatch() {
				if (this.locationWatcher) {
					return;
				}
				console.log('开始监听位置变化');
				// 直接使用前台定位
				this.startForegroundLocation();
			},
			startForegroundLocation() {
				const locationConfig = {
					type: 'gcj02',
					isHighAccuracy: true,
					success: () => {
						console.log('开启前台定位成功');
						this.setupLocationChange();
					},
					fail: (error) => {
						console.error('开启前台定位失败:', error);
						uni.showToast({
							title: '定位功能异常',
							icon: 'none'
						});
					}
				};

				console.log('正在启动位置更新...');
				wx.startLocationUpdate(locationConfig);
			},
			setupLocationChange() {
				console.log('开始设置位置变化监听');

				// 先清除可能存在的旧监听器
				try {
					wx.offLocationChange();
					console.log('已清除旧的位置监听器');
				} catch (e) {
					console.log('清除旧监听器时出错:', e);
				}

				// 监听位置变化事件
				wx.onLocationChange((res) => {
					// 检查位置是否真的变化
					if (this.hasLocationChanged(res)) {
						this.updateLocation(res);
					}
				});
			},
			hasLocationChanged(newLocation) {
				if (!this.latitude || !this.longitude) {
					console.log('首次定位，直接更新位置');
					return true;
				}

				// 计算位置变化距离（使用简单的经纬度差值计算）
				const latDiff = Math.abs(this.latitude - newLocation.latitude);
				const lngDiff = Math.abs(this.longitude - newLocation.longitude);

				// 设置更大的阈值，减少更新频率
				const threshold = 0.00005; // 大约5米的经纬度变化
				const hasChanged = latDiff > threshold || lngDiff > threshold;

				if (hasChanged) {
					console.log('检测到有效的位置变化:', {
						latDiff: latDiff.toFixed(6),
						lngDiff: lngDiff.toFixed(6),
						threshold: threshold
					});
				}

				return hasChanged;
			},
			updateLocation(res) {
				// 确保数据有效
				if (!res.latitude || !res.longitude) {
					console.log('收到无效的位置数据:', res);
					return;
				}

				this.latitude = res.latitude;
				this.longitude = res.longitude;

				// 上传位置信息
				this.uploadLocationInfo(res.latitude, res.longitude);
			},

			// 上传位置信息
			async uploadLocationInfo(latitude, longitude) {
				try {
					const params = {
						lat: latitude,
						lng: longitude
						// orderId: this.data.orderId // 假设订单ID从页面传递的数据中获取
					}
					const result = await commonApi.uploadLocation(params)
					console.log('位置上传成功:', result)
				} catch (error) {
					console.error('位置上传失败:', error)
				}
			},
			stopLocationWatch() {
				console.log('正在停止位置监听');
				try {
					wx.offLocationChange();
					wx.stopLocationUpdate();
					this.locationWatcher = null;
					console.log('位置监听已停止');
				} catch (e) {
					console.error('停止位置监听时出错:', e);
				}
			},
			// 更新地图标记点
			updateMarkers() {
				this.markers = [];

				// 添加出发地标记
				if (this.startLocation &&
					!isNaN(this.startLocation.latitude) &&
					!isNaN(this.startLocation.longitude)) {
					this.markers.push({
						id: 1,
						latitude: Number(this.startLocation.latitude),
						longitude: Number(this.startLocation.longitude),
						title: "出发地",
						iconPath: "/static/index/go.png",
						width: 30,
						height: 30
					});
				}

				// 添加目的地标记
				if (this.destinationLocation &&
					!isNaN(this.destinationLocation.latitude) &&
					!isNaN(this.destinationLocation.longitude)) {
					this.markers.push({
						id: 2,
						latitude: Number(this.destinationLocation.latitude),
						longitude: Number(this.destinationLocation.longitude),
						title: "目的地",
						iconPath: "/static/index/mudidi.png",
						width: 30,
						height: 30
					});
				}

				console.log('更新后的标记点:', this.markers)
			},
			// 根据经纬度获取地址
			getAddressByLocation(latitude, longitude, isInitial = false) {
				if (isInitial && !this.startAddress) { // 只在没有出发地地址时才设置
					// 如果是初始位置，直接设置经纬度作为出发地
					this.startLocation = {
						latitude: latitude,
						longitude: longitude
					};
					// 只在没有传入地址时才尝试获取地址
					if (!this.data.origin) {
						uni.getLocation({
							type: 'gcj02',
							geocode: true,
							success: (res) => {
								this.startAddress = res.address ||
									`${latitude.toFixed(6)},${longitude.toFixed(6)}`;
								this.updateMarkers();
							},
							fail: (error) => {
								console.error('获取地址失败:', error);
								this.startAddress = `${latitude.toFixed(6)},${longitude.toFixed(6)}`;
								this.updateMarkers();
							}
						});
					}
				}
			},
			// 更新路线
			updatePolyline() {
				if (!this.startLocation || !this.destinationLocation ||
					isNaN(this.startLocation.latitude) || isNaN(this.startLocation.longitude) ||
					isNaN(this.destinationLocation.latitude) || isNaN(this.destinationLocation.longitude)) return;

				this.polyline = [{
					points: [{
							latitude: Number(this.startLocation.latitude),
							longitude: Number(this.startLocation.longitude)
						},
						{
							latitude: Number(this.destinationLocation.latitude),
							longitude: Number(this.destinationLocation.longitude)
						}
					],
					color: '#2d8cf0',
					width: 4,
					arrowLine: true,
					borderColor: '#2d8cf0',
					borderWidth: 1
				}];

				// 调整地图视野以包含起点和终点
				const mapContext = uni.createMapContext('trajectoryMap');
				if (mapContext) {
					mapContext.includePoints({
						points: [{
								latitude: Number(this.startLocation.latitude),
								longitude: Number(this.startLocation.longitude)
							},
							{
								latitude: Number(this.destinationLocation.latitude),
								longitude: Number(this.destinationLocation.longitude)
							}
						],
						padding: [50, 50, 50, 50]
					});
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.trajectory-container {
		position: relative;
		width: 100%;
		height: 100vh;

		.map-area {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 1;
		}

		.info-card {
			position: fixed;
			right: 20rpx;
			bottom: 40rpx;
			width: 50%;
			background: rgba(255, 255, 255, 0.95);
			border-radius: 16rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
			padding: 24rpx 20rpx;
			z-index: 2;
			backdrop-filter: blur(10px);

			.drag-handle {
				width: 100%;
				height: 20rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-bottom: 10rpx;

				.handle-line {
					width: 60rpx;
					height: 6rpx;
					background: #ddd;
					border-radius: 3rpx;
				}
			}

			.label {
				font-size: 32rpx;
				font-weight: bold;
				color: #2d8cf0;
				margin-bottom: 20rpx;
				display: block;
				text-align: center;
			}

			.coords {
				display: flex;
				align-items: center;
				// margin-bottom: 10rpx;
			}

			.address-item {
				width: 100%;
				margin-top: 10rpx;
				align-items: center;

				.value {
					color: #333;
					font-weight: 500;
					margin-left: 8rpx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
				}
			}
		}
	}
</style>